package cn.slb.im.config;

import feign.RequestInterceptor;
import feign.RequestTemplate;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * @author NICK
 */
@Slf4j
@Configuration
public class ImFeignConfig {

    @Bean
    public RequestInterceptor requestInterceptor() {
        return new RequestInterceptor() {
            @Override
            public void apply(RequestTemplate requestTemplate) {
                log.info("Feign Interceptor execute start ...");
                // 拿到请求数据
                ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder
                        .getRequestAttributes();
                log.info("Feign get ServletRequestAttributes is : {} ", attributes);
                if (null != attributes) {
                    HttpServletRequest request = attributes.getRequest();
                    // 同步请求头数据
                    log.info("Feign set ServletRequestAttributes Cookie is : {} ", request.getHeader("Cookie"));
                    requestTemplate.header("Cookie", request.getHeader("Cookie"));
                }
                log.info("Feign Interceptor execute end ...");
            }
        };
    }

}
